package com.example.multiactivity

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class ThirdActivity : AppCompatActivity() {
    private val REQUEST_CODE_CAMERA = 1
    private val CAMERA_PERMISSION_REQUEST = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)

        // 检查相机权限，无权限则申请
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_GRANTED
        ) {
            // 权限已授予，直接打开相机
            openCamera()
        } else {
            // 申请相机权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.CAMERA),
                CAMERA_PERMISSION_REQUEST
            )
        }
    }

    // 打开系统相机
    private fun openCamera() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 检查是否有相机应用可处理该意图
        if (takePictureIntent.resolveActivity(packageManager) != null) {
            startActivityForResult(takePictureIntent, REQUEST_CODE_CAMERA)
        } else {
            Toast.makeText(this, "未找到相机应用", Toast.LENGTH_SHORT).show()
        }
    }

    // 处理权限申请结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限通过，打开相机
                openCamera()
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "需要相机权限才能使用拍照功能", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 处理相机返回的图片
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            // 获取相机返回的缩略图并显示
            val imageBitmap = data?.extras?.get("data") as? Bitmap
            if (imageBitmap != null) {
                findViewById<ImageView>(R.id.iv_photo).setImageBitmap(imageBitmap)
            } else {
                Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
}